import React, { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import {
  Button,
  Card,
  Divider,
  Grid,
  Image,
  List,
  NavBar,
  Popup,
  Stepper,
  Tag,
  Toast,
  Swiper,
} from "antd-mobile";
import styles from "../style/ProductDetailPage.module.css";
import ScoreDetails from "../img/scoredetail.png";
import ear from "../img/ear.png";
import xing from "../img/xing1.png";
import house from "../img/house.png";
import dian from "../img/dian.png";
import left from "../img/left.png";
// 调整接口结构以匹配新的数据结构
interface ProductDetail {
  productId: string | number;
  productImg: string;
  productPrice: string;
  productTitle: string;
  // 可以根据需要添加其他可选字段
  points?: number;
  original_points?: number;
  description?: string;
  stock?: number;
  limit?: number;
  delivery?: string;
  sales?: number;
  location?: string;
  colors?: string[];
  thickness?: string[];
}

const ProductDetailPage = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [product, setProduct] = useState<ProductDetail | null>(null);
  const [showPopup, setShowPopup] = useState(false);
  const [quantity, setQuantity] = useState(1);
  const [selectedColor, setSelectedColor] = useState("");
  const [selectedThickness, setSelectedThickness] = useState("");
  const [userPoints, setUserPoints] = useState(0);

  useEffect(() => {
    // 模拟从路由获取商品数据
    const productDataStr = localStorage.getItem("currentProduct");
    let productData = null;
    if (productDataStr) {
      try {
        productData = JSON.parse(productDataStr);
      } catch (error) {
        console.error("解析商品数据时出错:", error);
      }
    }

    setProduct(productData);
    if (productData) {
      setSelectedColor(productData.colors?.[0] || "");
      setSelectedThickness(productData.thickness?.[0] || "");
    }

    // 模拟获取用户积分
    const user = JSON.parse(localStorage.getItem("user") || "{}");
    setUserPoints(user?.data?.score || 0);
  }, [location.state]);

  const handleExchangeClick = () => {
    setShowPopup(true);
  };

  const handleClose = () => {
    setShowPopup(false);
  };

  const increaseQuantity = () => {
    if (quantity < (product?.limit || 10)) {
      setQuantity(quantity + 1);
    }
  };

  const decreaseQuantity = () => {
    if (quantity > 1) {
      setQuantity(quantity - 1);
    }
  };

  const confirmExchange = () => {
    if (!product) return;

    // 计算总积分
    const totalPoints = quantity * (parseFloat(product.productPrice) || 0);

    // 准备订单数据
    const orderData = {
      productId: product.productId,
      productImg: product.productImg,
      productTitle: product.productTitle,
      productPrice: product.productPrice,
      quantity,
      totalPoints,
      selectedColor,
      selectedThickness,
      timestamp: new Date().toISOString(),
    };

    // 存储到本地
    localStorage.setItem("currentOrder", JSON.stringify(orderData));

    // 导航到订单页面
    navigate("/pointspurchase");
  };

  if (!product) {
    return <div className="loading">加载中...</div>;
  }

  return (
    <div className={styles.productdetailcontainer}>
      <div className={styles.header} onClick={() => navigate(-1)}>
        <img src={left} alt="" />
      </div>

      <div className={styles.productcontent}>
        {/* 商品图片 */}
        <div className={styles.productimagecontainer}>
          <img
            src={product.productImg}
            alt={product.productTitle}
            className={styles.productimage}
          />
        </div>

        {/* 商品基本信息 */}
        <div className={styles.productinfosection}>
          <h2 className={styles.producttitle}>{product.productTitle}</h2>

          <div className={styles.productmetainfo}>
            <div className={styles.currentpoints}>
              <span className={styles.pointsicon}>{product.productPrice}</span>
              <span className={styles.pointsicon}>积分</span>
              {product.original_points && (
                <span className={styles.pointsicon}>
                  原价: {product.original_points}积分
                </span>
              )}
            </div>
          </div>

          <div className={styles.servicetags}>
            <span>正品保证</span>
            <span>破损包赔</span>
            <span>七天退换</span>
          </div>
        </div>

        {/* Promotions */}
        <div className={styles.promotionSection}>
          <div className={styles.promotionTitle}>
            <div className={styles.promotionItem}>
              <span className={styles.detail}>每人限购10件</span>
            </div>
            <div className={styles.promotionItem}>
              <span className={styles.styles}>
                满78元享包邮,不包邮地区；新疆，西藏，台湾
              </span>
            </div>
          </div>
          <div className={styles.dian}>
            <img src={dian} alt="" />
          </div>
        </div>

        {/* Guarantees */}
        <div className={styles.guaranteeSection}>
          <Grid style={{ display: "flex" }} columns={0} gap={0}>
            <Grid.Item>
              <div className={styles.guaranteeItem}>正品保证·</div>
            </Grid.Item>
            <Grid.Item>
              <div className={styles.guaranteeItem}>破损保障·</div>
            </Grid.Item>
            <Grid.Item>
              <div className={styles.guaranteeItem}>赠运费险·</div>
            </Grid.Item>
            <Grid.Item>
              <div className={styles.guaranteeItem}>极速退款·</div>
            </Grid.Item>
            <Grid.Item>
              <div className={styles.guaranteeItem}>七天退换</div>
            </Grid.Item>
          </Grid>
          <div className={styles.dian}>
            <img src={dian} alt="" />
          </div>
        </div>

        {/* Product Details */}
        <div className={styles.detailSection}>
          {/* <div className={detail.detailTitlebig}> */}
          <b className={styles.detailTitle}>
            <div className={styles.shopcolor}>产品参数</div>
            <div className={styles.dian}>
              <img src={dian} alt="" />
            </div>
          </b>
          {/* </div> */}
          <b className={styles.detailTitles}>
            <div className={styles.shopcolor}>选择 颜色分类</div>
            <div className={styles.dian}>
              <img src={dian} alt="" />
            </div>
          </b>
        </div>

        {/* 商品评价 */}
        <div className={styles.reviewssection}>
          <div className={styles.sectionheader}>
            <h3 className={styles.sectiontitle}>商品评价</h3>
            <span className={styles.reviewcount}>7362条</span>
          </div>

          <div className={styles.reviewcount}>
            <div className={styles.userinfo}>
              <div className={styles.useravatar}></div>
              <div className={styles.username}>*****2</div>
            </div>
            <div className={styles.reviewcontent}>
              宝贝收到了，质量很好，和描述一致，非常满意！
            </div>
            <div className={styles.reviewspec}>颜色分类：黑色</div>
          </div>
        </div>
      </div>

      {/* 底部操作栏 */}
      <div className={styles.footer}>
        <div className={styles.footerbtn}>
          <img src={ear} alt="" />
          <span className={styles.icon}>客服</span>
        </div>
        <div className={styles.footerbtn}>
          <img src={house} alt="" />
          <span className={styles.icon}>店铺</span>
        </div>
        <div className={styles.footerbtn}>
          <img src={xing} alt="" />
          <span className={styles.icon}>收藏</span>
        </div>
        <Button
          color="primary"
          className={styles.exchangebtn}
          onClick={handleExchangeClick}
        >
          立即兑换
        </Button>
      </div>

      {/* 兑换弹窗 */}
      {showPopup && (
        <div className={styles.popupoverlay} onClick={handleClose}>
          <div
            className={styles.popupcontent}
            onClick={(e) => e.stopPropagation()}
          >
            <div className={styles.productinfopopup}>
              <img
                src={product.productImg}
                alt={product.productTitle}
                className={styles.popupimage}
              />
              <div className={styles.productdetails}>
                <div className={styles.pointspopup}>
                  <span className={styles.pointsvaluepopup}>
                    {product.productPrice}积分
                  </span>
                </div>
                <div className={styles.popupheader}>
                  <div className={styles.userpoints}>剩余: {userPoints}</div>
                </div>
                <div className={styles.quantityselector}>
                  <div className={styles.quantitycontrol}>
                    <button
                      className={`${styles.quantitybtn} ${
                        quantity === 1 ? styles.disabled : ""
                      }`}
                      onClick={decreaseQuantity}
                      disabled={quantity === 1}
                    >
                      -
                    </button>
                    <span className={styles.quantityvalue}>{quantity}</span>
                    <button
                      className={`${styles.quantitybtn} ${
                        quantity === (product.limit || 10)
                          ? styles.disabled
                          : ""
                      }`}
                      onClick={increaseQuantity}
                      disabled={quantity === (product.limit || 10)}
                    >
                      +
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {product.colors && product.colors.length > 0 && (
              <div className={styles.optionselector}>
                <span className={styles.label}>颜色分类</span>
                <div className={styles.options}>
                  {product.colors.map((color) => (
                    <button
                      key={color}
                      className={`${styles.optionbtn} ${
                        selectedColor === color ? styles.selected : ""
                      }`}
                      onClick={() => setSelectedColor(color)}
                    >
                      {color}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {product.thickness && product.thickness.length > 0 && (
              <div className={styles.optionselector}>
                <span className={styles.label}>规格</span>
                <div className={styles.options}>
                  {product.thickness.map((item) => (
                    <button
                      key={item}
                      className={`${styles.optionbtn} ${
                        selectedThickness === item ? styles.selected : ""
                      }`}
                      onClick={() => setSelectedThickness(item)}
                    >
                      {item}
                    </button>
                  ))}
                </div>
              </div>
            )}

            <div className={styles.totalsection}>
              <span>合计:</span>
              <span className={styles.totalpoints}>
                {quantity * (parseFloat(product.productPrice) || 0)}积分
              </span>
            </div>

            <button className={styles.confirmbtn} onClick={confirmExchange}>
              立即兑换
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default ProductDetailPage;
